<?php
function _t($txt)
{
	static $trans;
	if(!isset($trans)) $trans = Zend_Registry::get('translate');
	return $trans->_($txt);
}

function debug($arr, $stop=false)
{
	echo '<pre>';
	print_r($arr);
	echo '</pre>';
	if($stop) die();
}

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
	protected $strModuleName;
	protected $strControllerName;
	protected $strActionName;
	
	protected function _initApp()
	{
		try
		{
			$loader = Zend_Loader_Autoloader::getInstance();
			$loader->setFallbackAutoloader(true);
			$loader->suppressNotFoundWarnings(true);
			$cache = $this->bootstrap('cachemanager')->getResource('cachemanager')->getCache('cache');
			Zend_Registry::set('cache', $cache);

			$db = $this->bootstrap('db')->getResource('db');
			Zend_Registry::set('db',$db);
			
			//init controller
			$objFront = $this->bootstrap('FrontController')->getResource('FrontController');
			$objRouter = $objFront->getRouter();

			$objRequest = new Zend_Controller_Request_Http();
			$strUri = $_SERVER['REQUEST_URI'];
			if(strpos($strUri, '/admin')) $strFile = 'uri_admin.ini';
			elseif(strpos($strUri, '/employers')) $strFile = 'uri_employers.ini';
			else $strFile = 'uri_jobseekers.ini';

			$strCacheName = str_replace('.', '_', $strFile);
			//if(($myRoutes=$cache->load($strCacheName))===FALSE)
			{
				$myRoutes = new Zend_Config_Ini(APP_PATH.'/configs/'.$strFile, 'rewrite');
				$cache->save($myRoutes, $strCacheName);
			}
			$objRouter->addConfig($myRoutes, 'routes')->route($objRequest);

			$this->strModuleName = $objRequest->getModuleName();
			$this->strControllerName = $objRequest->getControllerName();
			$this->strActionName = $objRequest->getActionName();
			$objFront->setDefaultModule( $this->strModuleName );

			$strLang = $objRequest->getParam('trans', 'vi');
			if($strLang != 'vi') $strLang = 'en';
			define('LANGUAGE', $strLang);

			Zend_Translate::setCache($cache);
			$strCacheName = 'Lang_'.$strLang.'_'.$this->strModuleName.'_'.$this->strControllerName;
			//Zend_Translate::clearCache($strCacheName);
			$strLangDir = APP_PATH.'/locales/'.$this->strModuleName.'/';
			$translate = new Zend_Translate('tmx', $strLangDir.'common.tmx', $strLang, array('tag'=>$strCacheName));
			Zend_Registry::set ( 'translate', $translate );

		}
		catch(Exception $exception)
		{
			$this->catchError($exception);
		}
	}

	protected function _initSession()
	{
		$strSession = strtoupper($this->strModuleName.'_USER');
		$sess = new Zend_Session_Namespace($strSession);
		if(empty($sess->userid))
		{
			$sess->userid = -1;
			$sess->firstname = 'Guest';
			$sess->email = '';
			$sess->referUrl = '';
		}
		$auth = Zend_Auth::getInstance();
		$auth->setStorage(new Zend_Auth_Storage_Session($strSession));
		if(!$auth->hasIdentity()) $auth->getStorage()->write($sess);

		switch($this->strModuleName)
		{
			case 'admin':
				$notLogged = array('login', 'password');
				if($sess->userid < 1 && !in_array($this->strActionName, $notLogged))
				{
					$frontController = Zend_Controller_Front::getInstance();
					$response = new Zend_Controller_Response_Http();
					$response->setRedirect(DOMAIN.'/'.$this->strModuleName.'/user/login');
					$frontController->setResponse($response);
				}
				break;
		}
		$this->AppUI = $sess;
	}

	private function catchError($exception)
	{
		if(APPLICATION_ENV == 'production' && !isset($_GET['debug']))
		{
			header('Location: '.DOMAIN);
			exit;
		}
		die("<div>Error detail: ".$exception->getMessage()."<p><pre>".$exception->getTraceAsString()."</pre></p></div>");
	}

	protected function _initView()
	{
		$configs = $this->getOption('smarty');
		$strTpldir = APP_PATH.'/data/templates_c/'.$this->strModuleName;
		if(!is_dir($strTpldir)) mkdir($strTpldir, 0777, true); // create template cache dir if not exists
		$configs['compile_dir'] = $strTpldir;
		$configs['template_dir'] = APP_PATH.'/modules/'.$this->strModuleName.'/views';
		
		$view = new Smarty_View($configs);
		$view->setScriptPath($configs['template_dir']);

		$view->PATH_JSS = DOMAIN.'/htdocs/';
		$view->LANGUAGE = LANGUAGE;
		$view->ROOT_URL = DOMAIN;
		$view->AppUI = $this->AppUI;
		$view->CURRENT_URL = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];

		if(LANGUAGE == 'vi')
		{
			$strLink = strtr($view->CURRENT_URL, array('/vi/'=>'/en/', 'vi.html'=>'en.html'));
			$strLink = preg_replace('/-vi$/Ui', '-en', $strLink);			
		}
		else
		{
			$strLink = strtr($view->CURRENT_URL, array('/en/'=>'/vi/', 'en.html'=>'vi.html'));
			$strLink = preg_replace('/-en$/Ui', '-vi', $strLink);
		}
		$view->CHANGE_LANGUAGE_URL = $strLink;
		switch($this->strModuleName)
		{
			case 'admin': $view->BASE_URL = DOMAIN.'/'.$this->strModuleName.'/'; break;
			case 'employers': $view->BASE_URL = DOMAIN.'/'.LANGUAGE.'/'.$this->strModuleName.'/'; break;
			default: $view->BASE_URL = DOMAIN.'/'.LANGUAGE;	break;
		}
		define('BASE_URL', $view->BASE_URL);

		$strRootName = $this->strModuleName.'_'.$this->strControllerName.'_'.$this->strActionName;
		$strKey = 'seo_title_'.$strRootName;
		if($strKey == _t($strKey)) $strKey = 'seo_title_default';
		$view->headTitle(_t($strKey));

		$strKey = 'seo_keyword_'.$strRootName;
		if($strKey == _t($strKey)) $strKey = 'seo_keywords_default';
		$view->headMeta()->setName('keywords', _t($strKey));

		$strKey = 'seo_description_'.$strRootName;
		if($strKey == _t($strKey)) $strKey = 'seo_description_default';
		$view->headMeta()->setName('description', _t($strKey));

		Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')
			->setViewSuffix($configs['suffix'])
			->setView($view);

		Zend_Registry::set('smarty', $view);
		return $view;
	}

	public function run()
	{
		try
		{
			$objFront = $this->getResource('FrontController');
			$objFront->throwExceptions(true);
			$objFront->dispatch();
			$objFront->returnResponse(true);
		}
		catch(Exception $exception)
		{
			$this->catchError($exception);
		}
	}
}